package com.mrzhou.gateway.config;

import com.mrzhou.gateway.handler.SwaggerResourceHandler;
import com.mrzhou.gateway.props.RouteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.filter.reactive.HiddenHttpMethodFilter;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 路由相关配置
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({RouteProperties.class})
public class RouterFunctionConfiguration {

    private final SwaggerResourceHandler swaggerResourceHandler;
    private static final String ALLOWED_HEADERS = "Tenant-Id, Cloud-Auth, Content-Type, Authorization, CREDENTIAL, X-XSRF-TOKEN, X-Requested-With, X-IJT";
    private static final String ALLOWED_METHODS = "GET,POST,PUT,DELETE,OPTIONS,HEAD";
    private static final String ALLOWED_ORIGIN = "*";
    private static final String MAX_AGE = "18000L";

    public RouterFunctionConfiguration(SwaggerResourceHandler swaggerResourceHandler) {
        this.swaggerResourceHandler = swaggerResourceHandler;
    }

    @Bean
    public WebFilter corsFilter() {
        return (serverWebExchange, webFilterChain) -> {
            ServerHttpRequest request= serverWebExchange.getRequest();
            if(CorsUtils.isCorsRequest(request)) {
                ServerHttpResponse response = serverWebExchange.getResponse();
                HttpHeaders headers = response.getHeaders();
                headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);
                headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
                headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
                headers.add("Access-Control-Max-Age", MAX_AGE);
                headers.add("Access-Control-Allow-Credentials", "true");
                if (request.getMethod() == HttpMethod.OPTIONS) {
                    response.setStatusCode(HttpStatus.OK);
                    return Mono.empty();
                }
            }
            return webFilterChain.filter(serverWebExchange);
        };
    }

    @Bean
    public RouterFunction routerFunction() {
        return RouterFunctions.route(RequestPredicates.GET("/swagger-resources")
                .and(RequestPredicates.accept(MediaType.ALL)), swaggerResourceHandler);
    }

    /**
     * 解决 Only one connection receive subscriber allowed.
     * 参考：https://github.com/spring-cloud/spring-cloud-gateway/issues/541
     */
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new HiddenHttpMethodFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
                return chain.filter(exchange);
            }
        };
    }

}
